<script setup>
import { ref } from "vue";
import { useUserStore } from "@/stores/userStore";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const userStore = useUserStore();
const router = useRouter();

// 1 准备登录表单数据
const loginForm = ref({
  userName: "blogadmin",
  password: "blogadmin",
  agree: true,
});
// 2 校验规则
const rules = {
  userName: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度为6-16位", trigger: "blur" },
  ],
  agree: [
    {
      validator: (rule, value, callback) => {
        // console.log(value);
        // 自定义校验逻辑
        // 勾选就通过 不勾选就不通过
        if (value) {
          callback();
        } else {
          callback(new Error("请勾选协议"));
        }
      },
    },
  ],
};
// 3 获取form实例做统一校验
const formRef = ref(null);
const login = () => {
  // const { mobile, password } = loginForm.value;
  formRef.value.validate(async (valid) => {
    // console.log(valid);
    if (valid) {
      // TODO 登录
      await userStore.getUserInfo(loginForm.value);
      // 提示用户登录结果
      ElMessage.success("登录成功");
      // 如果登录成功就跳转到首页
      router.replace({ path: "/" });
    }
  });
};
</script>

<template>
  <div class="login-container">
    <div class="form">
      <h1>登录</h1>
      <el-form ref="formRef" :rules="rules" :model="loginForm">
        <el-form-item prop="userName" label="账户">
          <el-input v-model="loginForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            show-password
            v-model="loginForm.password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item prop="agree">
          <el-checkbox v-model="loginForm.agree">用户平台协议</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 350px" @click="login"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss">
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #f4f4f4;
  width: 100%;
  background: url(../../assets//images/13.jpg) no-repeat center / cover;
  .form {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 400px;
    text-align: center;
    h1 {
      margin-bottom: 20px;
      font-size: 25px;
    }
  }
}
</style>